package com.campus.academic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.academic.job.dto.AuditResourcesDTO;
import com.campus.academic.job.dto.LearningResourcesDTO;
import com.campus.academic.job.dto.LearningResourcesUpdateDTO;
import com.campus.academic.job.entity.LearningResources;
import com.campus.academic.job.vo.LearningResourcesListVO;
import com.campus.academic.job.vo.LearningResourcesVO;
import com.campus.academic.mapper.LearningResourcesMapper;
import com.campus.academic.service.ILearningResourcesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.api.util.UserContext;
import com.campus.common.exception.ServiceException;
import com.campus.common.teacher.job.entity.Teacher;
import com.campus.common.teacher.mapper.TeacherMapper;
import com.campus.common.user.entity.pojo.User;
import com.campus.common.user.mapper.AuthMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 学习资源表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-16
 */
@Service
public class LearningResourcesServiceImpl extends ServiceImpl<LearningResourcesMapper, LearningResources> implements ILearningResourcesService {

    @Autowired
    private LearningResourcesMapper learningResourcesMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private AuthMapper authMapper;

    /**
     * 上传资源
     */
    @Override
    public void saveResource(LearningResourcesDTO learningResourcesDTO) {

        int userId = UserContext.getUserId();
        Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getUserId, userId));
        if (Optional.ofNullable(teacher).isEmpty()) {
            throw new ServiceException("未查询到该教师信息");
        }

        if (Optional.ofNullable(learningResourcesDTO).isEmpty()) {
            throw new ServiceException("传入参数异常");
        }

        LearningResources learningResources = new LearningResources();
        BeanUtils.copyProperties(learningResourcesDTO, learningResources);
        learningResources.setTeacherId(teacher.getId());
        learningResources.setUploadDate(LocalDateTime.now());
        int row = learningResourcesMapper.insert(learningResources);
        if (row < 1) {
            throw new ServiceException("上传资源失败");
        }

    }

    /**
     * 修改资源
     */
    @Override
    public void updateResource(LearningResourcesUpdateDTO learningResourcesUpdateDTO) {
        if (Optional.ofNullable(learningResourcesUpdateDTO).isEmpty()) {
            throw new ServiceException("传入参数异常");
        }

        List<LearningResources> list = learningResourcesMapper.selectList(new LambdaQueryWrapper<LearningResources>()
                .eq(LearningResources::getId, learningResourcesUpdateDTO.getId())
                .eq(LearningResources::getIsDeleted, 0));
        if (list.isEmpty()) {
            throw new ServiceException("待修改的资源信息不存在");
        }
        LearningResources learningResources = list.get(0);
        BeanUtils.copyProperties(learningResourcesUpdateDTO, learningResources);
        learningResources.setChangeDate(LocalDateTime.now());
        int row = learningResourcesMapper.updateById(learningResources);
        if (row < 1) {
            throw new ServiceException("修改资源信息失败");
        }
    }

    /**
     * 删除资源
     */
    @Override
    public void deleteResource(Integer id) {
        LearningResources resources = learningResourcesMapper.selectOne(new LambdaQueryWrapper<LearningResources>()
                .eq(LearningResources::getId, id)
                .eq(LearningResources::getIsDeleted, 0));
        if (Optional.ofNullable(resources).isEmpty()) {
            throw new ServiceException("未查询到该资源信息");
        }

        resources.setIsDeleted(true);
        resources.setChangeDate(LocalDateTime.now());
        int row = learningResourcesMapper.updateById(resources);
        if (row < 1) {
            throw new ServiceException("删除资源信息失败");
        }
    }

    /**
     * 获取我的资源列表
     */
    @Override
    public List<LearningResourcesListVO> getResourceList() {
        int userId = UserContext.getUserId();
        Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getUserId, userId));
        if (Optional.ofNullable(teacher).isEmpty()) {
            throw new ServiceException("未查询到该教师信息");
        }

        List<LearningResourcesListVO> list = new ArrayList<>();
        List<LearningResources> resourcesList = learningResourcesMapper.selectList(new LambdaQueryWrapper<LearningResources>()
                .eq(LearningResources::getTeacherId, teacher.getId())
                .eq(LearningResources::getIsDeleted, 0));

        for (LearningResources learningResources : resourcesList) {
            LearningResourcesListVO vo = new LearningResourcesListVO();
            BeanUtils.copyProperties(learningResources, vo);
            vo.setShowButtons(false);
            list.add(vo);
        }
        return list;
    }


    /**
     * 资源审核
     */
    @Override
    public void auditResource(AuditResourcesDTO auditResourcesDTO) {
        int userId = UserContext.getUserId();
        User user = authMapper.selectById(userId);
        if (Optional.ofNullable(user).isEmpty()) {
            throw new ServiceException("未查询到该用户信息");
        }

        LearningResources learningResources = learningResourcesMapper.selectOne(new LambdaQueryWrapper<LearningResources>()
                .eq(LearningResources::getId, auditResourcesDTO.getResourceId())
                .eq(LearningResources::getIsDeleted, 0));
        if (Optional.ofNullable(learningResources).isEmpty()) {
            throw new ServiceException("未查询到该资源信息");
        }

        //管理员身份
        if (user.getIdentity() == 2) {
            //已通过
            if (auditResourcesDTO.getAuditStatus() == 1) {
                learningResources.setAuditStatus(auditResourcesDTO.getAuditStatus());
                learningResources.setChangeDate(LocalDateTime.now());
                int row = learningResourcesMapper.updateById(learningResources);
                if (row < 1) {
                    throw new ServiceException("资源通过失败");
                }
            } else if (auditResourcesDTO.getAuditStatus() == 2) {
                //打回
                learningResources.setAuditStatus(auditResourcesDTO.getAuditStatus());
                learningResources.setIsDeleted(true);
                learningResources.setChangeDate(LocalDateTime.now());
                int row = learningResourcesMapper.updateById(learningResources);
                if (row < 1) {
                    throw new ServiceException("资源打回失败");
                }
            }
        } else {
            throw new ServiceException("无权限操作");
        }

    }

    /**
     * 获取所有资源列表
     */
    @Override
    public List<LearningResourcesVO> getAllResourceList() {
        List<LearningResources> resourcesList = learningResourcesMapper.selectList(new LambdaQueryWrapper<LearningResources>()
                .eq(LearningResources::getIsDeleted, 0));

        return resourcesList.stream().map(resource -> {
            Teacher teacher = teacherMapper.selectById(resource.getTeacherId());
            User user = authMapper.selectById(teacher.getUserId());
            LearningResourcesVO vo = new LearningResourcesVO();
            BeanUtils.copyProperties(resource, vo);
            vo.setTeacherName(user.getName());
            return vo;
        }).toList();
    }


    /**
     * 查询资源详情
     */
    @Override
    public LearningResourcesVO getResource(Integer id) {
        LearningResources learningResources = learningResourcesMapper.selectById(id);
        if (learningResources == null) {
            throw new ServiceException("未查询到该资源信息");
        }
        Teacher teacher = teacherMapper.selectById(learningResources.getTeacherId());
        User user = authMapper.selectById(teacher.getUserId());
        LearningResourcesVO vo = new LearningResourcesVO();
        BeanUtils.copyProperties(learningResources, vo);

        vo.setTeacherName(user.getName());
        return vo;
    }
}
